﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using clawSoft.clawPDF.Core.Helper;
using clawSoft.clawPDF.Core.Jobs;
using clawSoft.clawPDF.Core.Settings;
using clawSoft.clawPDF.ftplib.FtpLib;
using NLog;

namespace clawSoft.clawPDF.Core.Actions
{
    public class HttpAction : IAction, ICheckable
    {
        private const int ActionId = 29;
        private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

        private static readonly string InvalidPathCharRegex = string.Format(@"/\\|[{0}]+",
            Regex.Escape(new string(Path.GetInvalidPathChars()) + ":*?"));

        /// <summary>
        ///     Upload all output files with http
        /// </summary>
        /// <param name="job">The job to process</param>
        /// <returns>An ActionResult to determine the success and a list of errors</returns>
        public ActionResult ProcessJob(IJob job)
        {
            Logger.Debug("Launched http-Action");
            try
            {
                var result = HttpUpload(job);
                return result;
            }
            catch (Exception ex)
            {
                Logger.Error("Exception while upload file to http:\r\n" + ex.Message);
                return new ActionResult(ActionId, 999);
            }
        }

        /// <summary>
        ///     Check if the profile is configured properly for this action
        /// </summary>
        /// <param name="profile">The profile to check</param>
        /// <returns>ActionResult with configuration problems</returns>
        public ActionResult Check(ConversionProfile profile)
        {
            var actionResult = new ActionResult();
            if (profile.Http.Enabled)
            {
                if (string.IsNullOrEmpty(profile.Http.Server))
                {
                    Logger.Error("No Http server specified.");
                    actionResult.Add(ActionId, 100);
                }

                if (!Uri.TryCreate(profile.Http.Server, UriKind.RelativeOrAbsolute, out Uri url))
                {
                    Logger.Error("Not in URI format.");
                    actionResult.Add(ActionId, 101);
                }

                if (string.IsNullOrEmpty(profile.Http.UserName))
                {
                    Logger.Error("No Http username specified.");
                    actionResult.Add(ActionId, 102);
                }
            }

            return actionResult;
        }

        private ActionResult HttpUpload(IJob job)
        {
            var actionResult = Check(job.Profile);
            if (!actionResult)
            {
                Logger.Error("Canceled Http upload action.");
                return actionResult;
            }


            Logger.Debug("Creating http connection.\r\nServer: " + job.Profile.Http.Server + "\r\nUsername: " +
                         job.Profile.Http.UserName);

            try
            {
                //如果为true，文件存在时另存一份
                var dic = new Dictionary<string, string>();
                dic.Add("sender", job.Profile.Http.UserName.ToString());
                dic.Add("isCover", job.Profile.Http.EnsureUniqueFilenames ? "1" : "0");

                Logger.Info($@"1.开始上传文件：【{string.Join(",", job.OutputFiles)}】");
                var result = HttpHelper.HttpUploadFile(job.Profile.Http.Server, job.OutputFiles.ToArray(), dic, Encoding.UTF8);
                Logger.Info($@"2.上传文件完成：【{result}】");
            }
            catch (Exception ex)
            {
                Logger.Error($@"2.上载文件时出现异常：【{string.Join(",", job.OutputFiles)}】: \r\n {ex.Message}");
                return new ActionResult(ActionId, 107);
            }
            return new ActionResult();
        }
    }
}